import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.xslf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class PPTModifier {
    public static void main(String[] args) {
        String inputFilePath = "d://1.pptx";
        String outputFilePath = "d://2.pptx";

        try (XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(inputFilePath))) {
            List<XSLFSlide> slides = ppt.getSlides();
            // 获取幻灯片的默认字体设置
            XSLFSlide slideTemplate = ppt.getSlides().get(0);  // 使用第一页作为模板

            // 创建新的幻灯片
            XSLFSlide newSlide = ppt.createSlide(slideTemplate.getSlideLayout());

            // 遍历所有形状
            for (Shape shape : newSlide.getShapes()) {
                System.out.println(shape.getClass().getName() + " " + shape.getShapeName());
                if (shape instanceof XSLFAutoShape) {
                    newSlide.removeShape((XSLFShape) shape); // 删除该文本框
                }
            }

            // 创建文本框
            XSLFAutoShape textBox = newSlide.createAutoShape();
            textBox.setShapeType(ShapeType.RECT);
            textBox.setAnchor(new java.awt.Rectangle(100, 100, 400, 100)); // 设置文本框位置和大小

            // 设置文本内容
            textBox.setText("我爱中国");

            // 设置文本样式
            XSLFTextRun textRun = textBox.getTextParagraphs().get(0).getTextRuns().get(0);
            textRun.setFontFamily("宋体");
            textRun.setFontSize(18.0);
            textRun.setBold(true);
            textRun.setFontColor(java.awt.Color.YELLOW);

            // 保存修改后的PPTX文件
            try (FileOutputStream out = new FileOutputStream(outputFilePath)) {
                ppt.write(out);
            }

            System.out.println("PPTX文件已成功修改并保存！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
